package com.example.test.dialogfactory;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.paging.LoadStateAdapter;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.ejlchina.okhttps.HTTP;
import com.ejlchina.okhttps.OkHttpsException;
import com.example.test.dialogfactory.MainActivity51.Data;
import com.example.test.dialogfactory.MainActivity51.Footer;
import com.example.test.dialogfactory.MainActivity51.Repo;
import com.google.gson.Gson;
import easier.paging3.Paging3Adapter.SimpleDiffCallback;
import easier.paging3.Paging3RefreshAdapter;
import easier.safe.gson.GsonFactory;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Single;
import io.reactivex.rxjava3.core.SingleSource;
import java.io.Reader;
import java.net.ConnectException;
import java.util.List;

public class MainActivity52 extends AppCompatActivity {

    private static final String url = "https://api.github.com/search/repositories?sort=stars&q=Android";

    private final HTTP http = HTTP.builder().build();

    private RecyclerView mRecycler;
    private SwipeRefreshLayout mRefresh;

    public static void start( Context context ) {

        Intent starter = new Intent( context, MainActivity52.class );
        context.startActivity( starter );
    }

    @Override
    protected void onCreate( Bundle savedInstanceState ) {

        super.onCreate( savedInstanceState );
        setContentView( R.layout.activity_main52 );
        initView();
    }

    private void initView() {

        mRecycler = (RecyclerView) findViewById( R.id.recycler );
        mRecycler.setLayoutManager( new LinearLayoutManager( this ) );
        mRefresh = (SwipeRefreshLayout) findViewById( R.id.refresh );

        Paging3RefreshAdapter< Data > bridge = new Paging3RefreshAdapter< Data >(
            this,
            new SimpleDiffCallback<>(),
            mRecycler,
            mRefresh
        ) {
            @NonNull
            @Override
            public ViewHolder onCreateViewHolder( @NonNull ViewGroup parent, int viewType ) {

                return new ViewHolder( LayoutInflater.from( parent.getContext() ).inflate( R.layout.activity_main51_item,
                    parent, false ) );
            }

            @Override
            public void onBindViewHolder( @NonNull ViewHolder holder, int position ) {

                Data item = getItem( position );

                TextView mNameText;
                TextView mDescriptionText;
                TextView mStarCountText;

                mNameText = (TextView) holder.itemView.findViewById( R.id.name_text );
                mDescriptionText = (TextView) holder.itemView.findViewById( R.id.description_text );
                mStarCountText = (TextView) holder.itemView.findViewById( R.id.star_count_text );

                mNameText.setText( item.name );
                mDescriptionText.setText( item.description );
                mStarCountText.setText( String.format( "%d", item.stargazers_count ) );
            }

            @NonNull
            @Override
            protected LoadStateAdapter< ? > createFooter() {

                return new Footer( new OnClickListener() {
                    @Override
                    public void onClick( View v ) {

                        retryOrRefresh();
                    }
                } );
            }

            @Override
            protected SingleSource< List< Data > > loadData( int page, int pageSize ) {

                Reader inputStream = http.sync( url ).addUrlPara( "page", page ).addUrlPara( "per_page", pageSize ).get()
                    .getBody().toCharStream();
                Gson singletonGson = GsonFactory.getSingletonGson();
                Repo repo = singletonGson.fromJson( inputStream, Repo.class );
                return Single.just( repo.items ).observeOn( AndroidSchedulers.mainThread() );
            }

            @Override
            protected void notifyNotLoadingResult( int count ) {

                super.notifyNotLoadingResult( count );
                if ( count == 0 ) {
                    findViewById( R.id.empty ).setVisibility( View.VISIBLE );
                    findViewById( R.id.error ).setVisibility( View.GONE );
                } else {
                    findViewById( R.id.empty ).setVisibility( View.GONE );
                    findViewById( R.id.error ).setVisibility( View.GONE );
                }
            }

            @Override
            protected void notifyError( Throwable error ) {

                super.notifyError( error );
                if ( error instanceof ConnectException || error instanceof OkHttpsException ) {
                    findViewById( R.id.empty ).setVisibility( View.GONE );
                    findViewById( R.id.error ).setVisibility( View.VISIBLE );
                } else if ( error instanceof NullPointerException ) {
                    findViewById( R.id.empty ).setVisibility( View.GONE );
                    findViewById( R.id.error ).setVisibility( View.GONE );
                }
            }
        };

        bridge.build( getLifecycle() );
    }
}